<?php
/**
 * light Active Record implementation
 * each property should have a set{Property} method
 */
class DbRecord {

    /**
     * build a single record from sql query
     * @param string $sql
     * @param string $class
     * @return DbRecord
     */
    public static function selectRecord($sql,$class) {
        // execute query
        if (!$result=mysql_query($sql)) {
            return false;
        }
        if (!$line=mysql_fetch_assoc($result))
            return false;
        return new $class($line);
    }

    /**
     * build records from sql query
     * @param string $sql
     * @param string $class
     * @return array(DbRecord) (ou DbRecordSet ?)
     */
    public static function selectRecords($sql,$class) {
        // execute query
        if (!$result=mysql_query($sql)) {
            return false;
        }
        $records=array();
        /*while ($record=mysql_fetch_object($result,$class)) {
            $records[]=$record;
        }*/
        while ($line=mysql_fetch_assoc($result)) {
            $record=new $class($line);
            // $record->loadArray($line);
            $records[]=$record;
        }
        return $records;
    }

    /**
     * constructor
     * @param array $data properties values
     *
     */
    public function __construct($data=array()) {
        $this->loadArray($data);
    }

    /**
     * loads properties from an array
     * @param array $array data to load
     * @return int number of loaded properties
     */
    public function loadArray($array) {
        //$class=get_class($this);
        $loaded=0;
        foreach ($array as $key => $value) {
            $setMethod='set'.$key;
            if (method_exists($this,$setMethod) and $this->$setMethod($value))
                $loaded++;
            else {
                $this->$key=$value;
                $loaded++;
            }
        }
        return $loaded;
    }

    /**
     * loads record from database
     *
     * @return bool
     */
    public function load() {

    }
}